package com.stsmobile;

import com.stsmobile.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity {
	private static final CharSequence ERROR_MESSAGE = "Unable to connect\n" +
			"to the STS database.";
	/** Called when the activity is first created. */
	private Button login;
	//private ServerConnecter connecter;
	private String userID;
	private String userPass;
	
	@Override
	public void onResume(){
		super.onResume();
		STSApplication.loggingOut(false);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		//connecter = new ServerConnecter();
        setContentView(R.layout.main);
        
        final EditText usertextfield = (EditText) findViewById(R.id.etuser);
        final EditText passwordtextfield = (EditText) findViewById(R.id.etpass);
        

        login = (Button) findViewById(R.id.blogin);
        login.setOnClickListener(new View.OnClickListener() 
        {
			
			@Override
			public void onClick(View v) 
			{
				
				userID = usertextfield.getText().toString();
				userPass = passwordtextfield.getText().toString();
				
				String result = STSApplication.login(userID, userPass);
				
				if(result.contains("<success>"))
				{
					Intent nextpage = new Intent("com.stsmobile.Welcome");
					startActivity(nextpage);
					
				}
				else if((userID.equals("local") && userPass.equals("request"))){
					//TODO: This is simply a way to move to the next screen even
					//if you are not on the Duke network. Should be removed in the
					//final version.
					Intent nextpage = new Intent("com.stsmobile.Welcome");
					startActivity(nextpage);
				}
				else
				{
					CharSequence errorMessage="";
					
					//Get error message from server's response.
					int startMessage = result.indexOf("<msg>")+5;
					int endMessage = result.indexOf("</msg>");
					
					if(startMessage!=-1 && endMessage!=-1)
						errorMessage = result.substring(startMessage,endMessage);
						
					if(errorMessage.equals(""))
						errorMessage=ERROR_MESSAGE;
					
					//Display Error Message to User in a Popup
					Context cur_context = getApplicationContext();
					int duration = Toast.LENGTH_LONG;
					Toast displaymessage = Toast.makeText(cur_context, errorMessage, duration);
					displaymessage.show();
				}
			}
		});
	}    
    
}
//Friday Data